<template>
  <div class="select-wrap">
    <slot>
      <div v-if="label" class="label-wrap" :style="`width: ${labelWidth}`">
        <i v-if="required" class="red_color">*</i>
        <h5 v-if="bold">{{ label }}：</h5>
        <span v-else>{{ label }}：</span>
      </div>
    </slot>
    <el-select
      v-model="currentValue"
      :size="size"
      :clearable="clearable"
      :filterable="filterable"
      :disabled="disabled"
      :multiple="multiple"
      :collapse-tags="collapseTags"
      :placeholder="placeholder || `请选择${label}`"
      @change="handleChange"
    >
      <el-option
        v-for="(item, index) in options"
        :label="item[labelKey]"
        :value="item[valueKey]"
        :key="item[valueKey] + index"
      />
    </el-select>
  </div>
</template>
<script>
export default {
  props: {
    value: {
      type: String | Number | Array,
      default: ''
    },
    label: {
      type: String,
      default: ''
    },
    clearable: {
      type: Boolean,
      default: false
    },
    filterable: {
      type: Boolean,
      default: false
    },
    placeholder: {
      type: String,
      default: ''
    },
    options: {
      type: Array,
      default: () => []
    },
    bold: {
      type: Boolean,
      default: false
    },
    labelWidth: {
      type: String,
      default: 'auto'
    },
    disabled: {
      type: Boolean,
      default: false
    },
    multiple: {
      type: Boolean,
      default: false
    },
    collapseTags: {
      type: Boolean,
      default: true
    },
    size: {
      type: String
    },
    valueKey: {
      type: String,
      default: 'value'
    },
    labelKey: {
      type: String,
      default: 'label'
    },
    required: { // 必填星号标识
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      currentValue: '',
    }
  },
  computed: {
    labelStyle () {
      const style = `width: ${this.labelWidth}`
      return style
    }
  },
  watch: {
    value: {
      handler (val) {
        this.currentValue = val
      },
      immediate: true,
    }
  },
  methods: {
    handleChange () {
      this.$emit('update:value', this.currentValue)
      const data = this.options.find(item => item[this.valueKey] == this.currentValue) ?? {}
      this.$emit('change', { value: this.currentValue, data })
    },
  }
}
</script>
<style lang="less" scoped>
.select-wrap {
  display: flex;
  align-items: center;
}
.label-wrap {
  display: inline-block;
  text-align: right;
}
.red_color {
  color: #f56c6c;
}
</style>
